package account

import (
	"gitee.com/chenrh/finego/app"
	"gitee.com/chenrh/finego/backends/models"
	"gitee.com/chenrh/finego/backends/utils"
	"gitee.com/chenrh/gotoolkit/hash"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

// AccountController 用户管理
type AccountController struct {
	// Optionally: context is auto-binded by Iris on each request,
	// remember that on each incoming request iris creates a new UserController each time,
	// so all fields are request-scoped by-default, only dependency injection is able to set
	// custom fields like the Service which is the same for all requests (static binding).
	Ctx iris.Context
}

func (c *AccountController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("GET", "/reset_pass", "GetResetPass")
	b.Handle("POST", "/reset_pass", "PostResetPass")
}

func (c *AccountController) GetResetPass() mvc.Result {
	return mvc.View{
		Name: "user/account/reset_password.html",
		Data: iris.Map{
			"Title": "修改密码 | " + app.AppConfig.AppName,
		},
	}
}

func (c *AccountController) PostResetPass() {
	_, userCache := utils.UserCache(c.Ctx)
	user := models.PUB_USER{}
	user = user.GetModel(userCache.UserID)

	password_old := c.Ctx.FormValue("userpass")
	password_new := c.Ctx.FormValue("userpass_new")

	if len(password_old) == 0 {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "原密码不能为空"})
		return
	}

	if len(password_new) == 0 {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "新密码不能为空"})
		return
	}

	loginlog := models.PUB_USER_LOG{
		NickName:  user.NickName,
		UserCode:  user.UserCode,
		LogInfo:   "修改密码",
		LogIP:     c.Ctx.RemoteAddr(),
		UserAgent: c.Ctx.GetHeader("user-agent"),
	}

	password := hash.Md5Encode(password_old + user.LoginSalt)
	if password != user.LoginPass {
		loginlog.LogInfo = "修改密码失败，原密码不匹配"
		go user.InsertLoginLog(loginlog)
		c.Ctx.JSON(iris.Map{"flag": false, "msg": loginlog.LogInfo})
		return
	}

	saltstr := hash.RandomString(6)
	password = hash.Md5Encode(password_new + saltstr)

	db := app.GetDB()
	// defer db.Close()

	// 使用 struct 更新多个属性，只会更新其中有变化且为非零值的字段
	db.Model(&user).Updates(models.PUB_USER{LoginSalt: saltstr, LoginPass: password})

	loginlog.LogInfo = "密码修改成功"
	go user.InsertLoginLog(loginlog)
	c.Ctx.JSON(iris.Map{"flag": true, "msg": loginlog.LogInfo})
	return
}
